package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mall.entity.User;
import com.mall.exception.ServiceException;
import com.mall.mapper.UserMapper;
import com.mall.service.UserService;

import javax.annotation.Resource;
import com.mall.enums.*;
import com.mall.util.StringUtil;
import com.mall.util.TokenUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: liang
 * @time: 2024-01-17 11:22
 */
@Component
@Mapper
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    private final Environment env;

    public UserServiceImpl(Environment env, UserMapper userMapper) {
        this.env = env;
        this.userMapper = userMapper;
    }


    @Override
    public Map<String, Object> login(String phone, String password) {


        User dbUser = userMapper.selectByPhoneAndPassword(phone, password);
        if (dbUser == null) {
            throw new ServiceException(CodeNumEntity.USER_ERROR.getCode(),"用户名或密码错误");
        }
        User updateTimeUser = new User();
        updateTimeUser.setUserId(dbUser.getUserId());
        updateTimeUser.setUpdateTime(new Date());
        userMapper.updateSelective(updateTimeUser);
        //is match
        //update login time

//        生成token
        String token = TokenUtils.createToken(dbUser.getUserId(), env.getProperty("jwt.sign.property"));

        Map<String, Object> map = new HashMap<>();
        map.put("user",dbUser);
        map.put("token", token);

        return map;
    }

    @Override
    public User register(User user) {
        //check phone is duplicate
        User dbUser = userMapper.selectByPhone(user.getPhone());
        if (dbUser != null) {
            throw new ServiceException("电话已注册！");
        }
        //genrarate userId

        String userId = StringUtil.getSubTimeNumString(7, 7);
        if(userId == null){
            throw new ServiceException(CodeNumEntity.FAIL.getCode(),CodeNumEntity.FAIL.getMessage());
        }

        user.setUserId(userId);
        //update createTime and upateTime

        int i = userMapper.insertSelective(user);
        if (i == 0) {
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(),CodeNumEntity.DATABASE_ERROR.getMessage());
        }
        return user;
    }

    @Override
    public User uploadAvatar(String url, String userId) {
        User user = new User();
        user.setAvatar(url);
        user.setUserId(userId);
        //updateTie
        user.setUpdateTime(new Date());
        int i = userMapper.updateSelective(user);
        if (i == 0) {
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(),CodeNumEntity.DATABASE_ERROR.getMessage());
        }
        return user;


    }

    @Override
    public User modifyUserInfo(User user) {

        //judge phone is change
        User dbUser = userMapper.selectByUserId(user.getUserId());
        if(dbUser == null){
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(),CodeNumEntity.DATABASE_ERROR.getMessage());
        }
        //phone number is change
        if (!dbUser.getPhone().equals(user.getPhone())) {
            //judge phone number is duplicate
            if(userMapper.selectByPhone(user.getPhone()) != null){
                throw new ServiceException("该号码已被注册");
            }
        }
        user.setUpdateTime(new Date());
        int i= userMapper.updateSelective(user);
        if (i == 0) {
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(),CodeNumEntity.DATABASE_ERROR.getMessage());
        }
        //
        return userMapper.selectByUserId(user.getUserId());
    }

    @Override
    public User queryUserByUserId(String userId) {

        if(userId == null){//userId为空
            return TokenUtils.getCurrentUser();
        }

        return userMapper.selectByUserId(userId);
    }

    @Override
    public User queryUserByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    public boolean resetPass(User user) {
        return userMapper.update(user,new UpdateWrapper<User>().eq("phone",user.getPhone())) > 0;
    }

    //修改密码 实现
    @Override
    public User modifyPassword(String phone, String password) {

        //判断号码在数据库中是否存在
        User dbUser = userMapper.selectByPhone(phone);
        if(dbUser == null){
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(),CodeNumEntity.DATABASE_ERROR.getMessage());
        }
        //将密码改为新密码
        dbUser.setPassword(password);
        dbUser.setUpdateTime(new Date());
        //更新数据库
        int i= userMapper.updateSelective(dbUser);
        if (i == 0) {
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(),CodeNumEntity.DATABASE_ERROR.getMessage());
        }
        //
        return userMapper.selectByUserId(dbUser.getUserId());
    }

    @Override
    public int uploadDefaultAvatar(String url) {
        return userMapper.insertDefaultAvatar(url);
    }
}